import pygame
from constants import TextBoxConfig

# 单个文本框类
class TextBox:
    def __init__(self, rect, index):
        self.rect = rect  # 文本框矩形区域
        self.index = index  # 文本框索引（用于标签显示）
        self.font = pygame.font.SysFont(TextBoxConfig.FONT_NAME, TextBoxConfig.FONT_SIZE)
        self.label_font = pygame.font.SysFont(TextBoxConfig.FONT_NAME, TextBoxConfig.LABEL_FONT_SIZE, bold=True)
        self.text = ""  # 文本内容
        self.scroll_offset = 0  # 滚动偏移量
        self.is_active = False  # 激活状态
        self.is_dragging = False  # 滚动条拖动状态
        self.drag_start = 0  # 拖动起始位置

    def _get_scroll_rect(self):
        """获取滚动条矩形区域"""
        return pygame.Rect(
            self.rect.right - TextBoxConfig.SCROLL_BAR_WIDTH - TextBoxConfig.PADDING,
            self.rect.top + TextBoxConfig.PADDING,
            TextBoxConfig.SCROLL_BAR_WIDTH,
            self.rect.height - 2 * TextBoxConfig.PADDING
        )

    def _wrap_text(self, text):
        """自动换行处理"""
        lines = []
        current_line = ""
        max_width = self.rect.width - 2 * TextBoxConfig.PADDING - TextBoxConfig.SCROLL_BAR_WIDTH
        for char in text:
            if char == '\n':
                lines.append(current_line)
                current_line = ""
                continue
            test_line = current_line + char
            if self.font.size(test_line)[0] <= max_width:
                current_line = test_line
            else:
                lines.append(current_line)
                current_line = char
        if current_line:
            lines.append(current_line)
        return lines

    def _get_line_count(self):
        """获取行数"""
        return len(self._wrap_text(self.text))

    def _get_total_height(self, line_count):
        """计算内容总高度"""
        return line_count * (TextBoxConfig.FONT_SIZE + TextBoxConfig.LINE_SPACING)

    def handle_event(self, event):
        """处理事件"""
        if event.type == pygame.MOUSEBUTTONUP:
            # 检测文本框点击
            if self.rect.collidepoint(event.pos):
                self.is_active = True
                # 检测滚动条点击
                if self._get_scroll_rect().collidepoint(event.pos):
                    self.is_dragging = True
                    self.drag_start = event.pos[1]
            else:
                self.is_active = False
                self.is_dragging = False

        elif event.type == pygame.MOUSEBUTTONUP:
            self.is_dragging = False

        elif event.type == pygame.MOUSEMOTION and self.is_dragging:
            self._update_scroll_offset(event.pos[1])

        # 处理键盘输入
        if self.is_active and event.type == pygame.KEYDOWN:
            if event.key == pygame.K_BACKSPACE:
                self.text = self.text[:-1]
            elif event.key == pygame.K_RETURN:
                self.text += '\n'
            else:
                self.text += event.unicode  # 支持中文输入
        return

    def _update_scroll_offset(self, current_y):
        """更新滚动偏移量"""
        dy = current_y - self.drag_start
        line_count = self._get_line_count()
        total_height = self._get_total_height(line_count)
        visible_height = self.rect.height - 2 * TextBoxConfig.PADDING

        if total_height <= visible_height:
            self.scroll_offset = 0
            return

        max_offset = total_height - visible_height
        new_offset = self.scroll_offset + dy
        self.scroll_offset = max(0, min(new_offset, max_offset))
        self.drag_start = current_y

    def draw(self, surface):
        """绘制文本框"""

        # 创建透明背景表面（使用SRCALPHA模式）
        bg_surface = pygame.Surface((self.rect.width, self.rect.height), pygame.SRCALPHA)
        # 绘制半透明背景
        pygame.draw.rect(bg_surface, TextBoxConfig.BG_COLOR, (0, 0, self.rect.width, self.rect.height))
        # 绘制边框（黑色）
        border_width = TextBoxConfig.BORDER_ACTIVE_WIDTH if self.is_active else TextBoxConfig.BORDER_WIDTH
        border_color = TextBoxConfig.BORDER_ACTIVE_COLOR if self.is_active else TextBoxConfig.BORDER_COLOR
        pygame.draw.rect(bg_surface, border_color, (0, 0, self.rect.width, self.rect.height), border_width)
        # 绘制到屏幕
        surface.blit(bg_surface, (self.rect.x, self.rect.y))

        # 绘制标签
        label = self.label_font.render(f"文本框 {self.index + 1}", True, TextBoxConfig.TEXT_COLOR)
        surface.blit(label, (self.rect.x + 10, self.rect.y - 30))

        # 设置裁剪区域
        clip_rect = pygame.Rect(
            self.rect.x + TextBoxConfig.PADDING,
            self.rect.y + TextBoxConfig.PADDING,
            self.rect.width - 2 * TextBoxConfig.PADDING - TextBoxConfig.SCROLL_BAR_WIDTH,
            self.rect.height - 2 * TextBoxConfig.PADDING
        )
        old_clip = surface.get_clip()
        surface.set_clip(clip_rect)
        # 绘制文本
        y = self.rect.y + TextBoxConfig.PADDING - self.scroll_offset
        for line in self._wrap_text(self.text):
            text_surface = self.font.render(line, True, TextBoxConfig.TEXT_COLOR)
            surface.blit(text_surface, (self.rect.x + TextBoxConfig.PADDING, y))
            y += TextBoxConfig.FONT_SIZE + TextBoxConfig.LINE_SPACING

        surface.set_clip(old_clip)
        self._draw_scrollbar(surface)

    def _draw_scrollbar(self, surface):
        """绘制滚动条"""
        line_count = self._get_line_count()
        total_height = self._get_total_height(line_count)
        visible_height = self.rect.height - 2 * TextBoxConfig.PADDING

        if total_height <= visible_height:
            return

        scroll_rect = self._get_scroll_rect()
        thumb_height = max(30, (visible_height / total_height) * visible_height)
        thumb_pos = (self.scroll_offset / total_height) * (visible_height - thumb_height)

        pygame.draw.rect(surface, TextBoxConfig.SCROLL_BAR_COLOR, scroll_rect)
        pygame.draw.rect(surface, TextBoxConfig.THUMB_COLOR, pygame.Rect(
            scroll_rect.x,
            scroll_rect.y + thumb_pos,
            scroll_rect.width,
            thumb_height
        ))


# 文本框管理器类
class TextBoxManager:
    BOXES = [
        pygame.Rect(200, 50, 300, 250),  # 左上
        pygame.Rect(520, 50, 300, 250),  # 右上
        pygame.Rect(200, 350, 300, 250),  # 左下
        pygame.Rect(520, 350, 300, 250)  # 右下
    ]

    def __init__(self):
        self.text_boxes = [
            TextBox(self.BOXES[i], i) for i in range(4)
        ]

    def handle_event(self, event):
        """分发事件到所有文本框"""
        for box in self.text_boxes:
            box.handle_event(event)

    def draw(self, surface):
        """绘制所有文本框"""
        for box in self.text_boxes:
            box.draw(surface)